package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.ExcelUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.module.service.impl.DeviceWeldingRecordServiceImpl;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 传感器
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/device/welding/record")
public class DeviceWeldingRecordController extends BaseController {

    @Autowired
    private DeviceWeldingRecordService deviceRecordService;
    @Autowired
    private DeviceWeldingRecordImgService deviceWeldingRecordImgService;
    @Resource
    private ShopService shopService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private FireWorkService fireWorkService;

    @Value("${projecturl.imgurl}")
    private String imgurl;

    @Log("查询设备页面")
    @GetMapping("")
    @RequiresPermissions("module:device:welding:record:device")
    String device(Model model) {
        UserDO user = getUser();
        model.addAttribute("isSelf",0);
        model.addAttribute("deviceType",0);

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }

        if(user.getUserType() == 10 || user.getUserType() == 4){
            wrapper.eq("id", user.getShopId());
        }else if(user.getUserType() == 2){
            wrapper.eq("group_id", user.getGroupId());
        }else if(user.getUserType() == 3){
            wrapper.eq("pianqu_id", user.getPianquId());
        }else{
            if (user.getPianquId() != null && user.getPianquId() > 0) {
                wrapper.eq("pianqu_id", user.getPianquId());
            }
        }
        List<Shop> shopList = shopService.list(wrapper);
        model.addAttribute("shopList",shopList);
        return "module/device/welding/record/record";
    }

    @Log("查询设备页面")
    @GetMapping("/{deviceType}")
    @RequiresPermissions("module:device:welding:record:device")
    String device(Model model, @PathVariable("deviceType") Integer deviceType) {
        UserDO user = getUser();
        model.addAttribute("isSelf",0);
        model.addAttribute("deviceType",deviceType);

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }

        if(user.getUserType() == 10 || user.getUserType() == 4){
            wrapper.eq("id", user.getShopId());
        }else if(user.getUserType() == 2){
            wrapper.eq("group_id", user.getGroupId());
        }else if(user.getUserType() == 3){
            wrapper.eq("pianqu_id", user.getPianquId());
        }else{
            if (user.getPianquId() != null && user.getPianquId() > 0) {
                wrapper.eq("pianqu_id", user.getPianquId());
            }
        }

        List<Shop> shopList = shopService.list(wrapper);
        model.addAttribute("shopList",shopList);
        return "module/device/welding/record/record";
    }

    @Log("查询设备页面")
    @GetMapping("/self")
    @RequiresPermissions("module:device:welding:record:self")
    String deviceSelf(Model model) {
        model.addAttribute("isSelf",1);
        return "module/device/welding/record/record";
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions(value = {"module:device:welding:record:device","module:device:welding:record:self"}, logical = Logical.OR)
    public DataTableLayUI<DeviceWeldingRecord> list(DataTableLayUI<DeviceWeldingRecord> condition) {

        UserDO user = getUser();
        Map<String, Object> map = condition.getSearchParams();
        String isSelf = map.containsKey("search_eq_isSelf") ? map.get("search_eq_isSelf").toString() : null;
        String deviceType = map.containsKey("search_eq_deviceType") ? map.get("search_eq_deviceType").toString() : null;
        String device_id = map.containsKey("search_eq_deviceId") ? map.get("search_eq_deviceId").toString() : null;
        String begin_date = map.containsKey("begin_date") ? map.get("begin_date").toString() : null;
        String end_date = map.containsKey("end_date") ? map.get("end_date").toString() : null;
        String pianquId = map.containsKey("search_eq_pianquId") ? map.get("search_eq_pianquId").toString() : null;
        String shopId = map.containsKey("shopId") ? map.get("shopId").toString() : null;

        Map<String,Object> map1 = new HashMap<>();

        QueryWrapper<DeviceWeldingRecord> qw = new QueryWrapper<>();
        qw.eq("is_self", isSelf);
        map1.put("is_self", isSelf);
        if(StrUtil.isNotEmpty(device_id)){
            qw.eq("device_id", device_id);
            map1.put("device_id", device_id);
        }
        if(StrUtil.isNotEmpty(deviceType)){
            qw.eq("device_type", deviceType);
            map1.put("device_type", deviceType);
        }

        if(user.getUserType() == 10){
            qw.eq("shop_id",user.getShopId());
            map1.put("shop_id",user.getShopId());
        }else if(user.getUserType() == 2){
            map1.put("group_id",user.getGroupId());
        }else if(user.getUserType() == 3){
            map1.put("pianqu_id",user.getPianquId());
        }else if(user.getUserType() == 4){
            map1.put("shop_id",user.getShopId());
        }
        if(StrUtil.isNotEmpty(pianquId)){
            map1.put("pianqu_id", pianquId);
        }
        if(StrUtil.isNotEmpty(shopId)){
            map1.put("shop_id", shopId);
        }


        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date,end_date);

            map1.put("begin_time", begin_date +" 00:00:00");
            map1.put("end_time", end_date +" 23:59:59");
        }
        qw.orderByDesc("create_time");
        condition.setQw(qw);

        Page<DeviceWeldingRecord> page = deviceRecordService.getPage(condition);
        List<DeviceWeldingRecord> list = deviceRecordService.getPageByUserId(page,map1);
        DataTableLayUI<DeviceWeldingRecord> dt = deviceRecordService.pageSearchCustom(page,list,condition);
        List<DeviceWeldingRecord> listData = dt.getData();

        for (DeviceWeldingRecord record : listData){
            Date beginTime = record.getUseBeginTime();
            Date backTime = record.getRebackTime();
            if(beginTime!= null){
                if(new Date().getTime() > record.getUseEndTime().getTime() && record.getState() == 1){// 固定是只需要生产经理批
                    if(record.getIsSafe() == 0
                            && (record.getDepartCheckState() == null || record.getDepartCheckState() == 0)){ //isSafe 安全类型 0 - 非固定  1 - 固定
                        record.setShowUseTime("未审核");
                    }else if(record.getIsSafe() == 1 && (record.getManagerCheckState() == null || record.getManagerCheckState() == 0)){
                        record.setShowUseTime("未审核");
                    }else if (record.getDepartCheckState() == 1 || record.getManagerCheckState() == 1 && backTime == null){
                        record.setShowUseTime("未归还");
                    }
                }else{
                    if (record.getState() == 2){
                        if(record.getIsSafe() == 0 && (record.getDepartCheckState() == null || record.getDepartCheckState() == 0)){
                            record.setShowUseTime("未使用");
                        }else if(record.getIsSafe() == 1 && (record.getManagerCheckState() == null || record.getManagerCheckState() == 0)){
                            record.setShowUseTime("未使用");
                        }
                    }
                    if(backTime != null && StrUtil.isEmpty(record.getShowUseTime())){
                        String time = DateUtils.getDistanceTimeByDate(beginTime,backTime , 1);
                        // 超过8小时显示8小时
                        if(time.contains("天")){
                            record.setShowUseTime("8小时");
                        }else if(time.contains("小时")){
                            String hours = "";
                            int index = time.indexOf("小时");
                            if (Integer.parseInt(time.substring(0, index)) >= 8){
                                record.setShowUseTime("8小时");
                            }else {
                                record.setShowUseTime(time);
                            }
                        }else {
                            record.setShowUseTime(time);
                        }
                    }else if (backTime == null && StrUtil.isEmpty(record.getShowUseTime())){
                        record.setShowUseTime("未归还");
                    }
                }
            }
        }

//        DataTableLayUI<DeviceWeldingRecord> dt = deviceRecordService.pageSearchLayUI(condition);
        return dt;
    }


    @GetMapping("/exportExcel")
    public void testExportExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("isSelf") Integer isSelf,@RequestParam("deviceType") Integer deviceType,
                                @RequestParam("pianquId") Integer pianquId, HttpServletResponse response){

        UserDO user = getUser();

        Map<String,Object> map1 = new HashMap<>();
        QueryWrapper<DeviceWeldingRecord> qw = new QueryWrapper<>();
        qw.eq("is_self",isSelf);
        qw.eq("device_type",deviceType);
        map1.put("is_self", isSelf);
        map1.put("device_type",deviceType);

        if(user.getUserType() == 10){
            qw.eq("shop_id",user.getShopId());
            map1.put("shop_id",user.getShopId());
        }else if(user.getUserType() == 2){
            map1.put("group_id",user.getGroupId());
        }else if(user.getUserType() == 3){
            map1.put("pianqu_id",user.getPianquId());
        }else if(user.getUserType() == 4){
            map1.put("shop_id",user.getShopId());
        }

        if(pianquId!= null){
            map1.put("pianqu_id", pianquId);
        }


        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");

            map1.put("begin_time", begin_date +" 00:00:00");
            map1.put("end_time", end_date +" 23:59:59");

        }else{
            begin_date = DateUtils.getMonthStr(new Date()) + "-01";
            end_date = DateUtils.getDay();
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");

            map1.put("begin_time", begin_date +" 00:00:00");
            map1.put("end_time", end_date +" 23:59:59");
        }
        qw.orderByDesc("create_time");
        qw.eq("state",2);
//        List<DeviceWeldingRecord> records = deviceRecordService.list(qw);
        List<DeviceWeldingRecord> records = deviceRecordService.getListByUserId(map1);

        records.forEach(record->{
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));

            if(record.getRebackTime()!= null){
                String times = DateUtils.getDistanceTimeByDate(record.getUseBeginTime(), record.getRebackTime(),0);
//                record.setUseTimeStr(times);
                if(times.contains("天")){
                    record.setUseTimeStr("8小时");
                }else if(times.contains("小时")){
                    String hours = "";
                    int index = times.indexOf("小时");
                    if (Integer.parseInt(times.substring(0, index)) >= 8){
                        record.setUseTimeStr("8小时");
                    }else {
                        record.setUseTimeStr(times);
                    }
                }else {
                    record.setUseTimeStr(times);
                }
            }

            record.setUseBeginTimeStr(DateUtils.getTime(record.getUseBeginTime()));
            if(new Date().getTime() > record.getUseEndTime().getTime() && record.getUseState() == 1 && record.getDepartCheckState() == 0){
                record.setShowUseTime("未审核");
            }else{
                record.setUseEndTimeStr(DateUtils.getTime(record.getUseEndTime()));
            }


            if(record.getIsSafe() == 0){
                record.setIsSafeStr("非固定区域");
            }else{
                record.setIsSafeStr("固定区域");
            }
        });

        ExcelUtils.writeExcel(response, records, DeviceWeldingRecord.class, System.currentTimeMillis() + "_电焊机申请记录.xlsx");
    }


    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions(value = {"module:device:welding:record:edit","module:device:welding:record:self"}, logical = Logical.OR)
    String edit(@PathVariable("id") Integer id, Model model) {
        DeviceWeldingRecord record = deviceRecordService.findById(id);
        model.addAttribute("record", record);
        return "module/device/welding/record/detail";
    }

    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:device:welding:record:add")
    public R save(@Valid DeviceWeldingRecord record) {
        boolean bl = deviceRecordService.save(record);
        if (bl) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:device:welding:record:edit")
    public R update(@Valid DeviceWeldingRecord record) {
        deviceRecordService.updateById(record);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:device:welding:record:remove")
    public R remove( Integer id) {
        if (deviceRecordService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @Log("设备详情页面")
    @GetMapping("/detail/{id}")
//    @RequiresPermissions(value = {"module:device:welding:record:edit","module:device:welding:record:self"}, logical = Logical.OR)
    String detail(@PathVariable("id") Integer id, Model model) {
        DeviceWeldingRecord record = deviceRecordService.findById(id);
        List<DeviceWeldingRecordImg> imgs = deviceWeldingRecordImgService.selectListByColumn("record_id", id);
        List<String> workPositionImgs = imgs.stream().filter(img -> img.getImgType() == 0 && img.getImgUrl() != null).map(img -> imgurl + img.getImgUrl()).collect(Collectors.toList());
        List<String> securityImgs = imgs.stream().filter(img -> img.getImgType() == 1 && img.getImgUrl() != null).map(img -> imgurl + img.getImgUrl()).collect(Collectors.toList());
        record.setWorkPositionImgs(workPositionImgs);
        record.setSecurityImgs(securityImgs);

        if(record.getIsSafe() == 0
                && (record.getDepartCheckState() == null || record.getDepartCheckState() == 0)){ //isSafe 安全类型 0 - 非固定  1 - 固定
            record.setCheckStateShow("未审核");
        }else if(record.getIsSafe() == 1 && (record.getManagerCheckState() == null || record.getManagerCheckState() == 0)){
            record.setCheckStateShow("未审核");
        }else if (record.getIsSafe() == 0 && record.getDepartCheckState() != null && record.getDepartCheckState() == 1){
            record.setCheckStateShow("审核已通过");
            record.setCheckStateResultShow(record.getDepartCheckResult());
        }else if (record.getIsSafe() == 1 && record.getManagerCheckState() != null && record.getManagerCheckState() == 1){
            record.setCheckStateShow("审核已通过");
            record.setCheckStateResultShow(record.getManagerCheckResult());
        }

        model.addAttribute("record", record);
        return "module/device/welding/record/recordDetail";
    }

    /**
     * 归还
     */
    @Log("归还设备")
    @PostMapping( "/reback")
    @ResponseBody
    @RequiresPermissions("module:device:welding:record:reback")
    public R reback(Integer id) {
        DeviceWeldingRecord deviceWeldingRecord = deviceRecordService.findById(id);
//        if (deviceWeldingRecord != null && deviceWeldingRecord.getUseState() != null && deviceWeldingRecord.getUseState() == 2) {
            deviceWeldingRecord.setState(2);
            deviceWeldingRecord.setRebackTime(new Date());
            deviceRecordService.updateById(deviceWeldingRecord);
            DeviceWelding deviceWelding = deviceWeldingService.findById(deviceWeldingRecord.getDeviceId());
            if (deviceWelding != null){
                deviceWelding.setUseState(0);
                deviceWeldingService.updateById(deviceWelding);
            }
            return R.ok("归还成功！");
//        }
//        return R.error("归还失败！");
    }
}
